<?php

namespace modules\point\controller;

class AdminController extends \core\AdminController
{
    protected $model = [
        'point' => "\modules\point\model\PointModel",
        'point_his' => "\modules\point\model\PointHisModel",
    ];

    /**
     * 积分列表
     * @permission 积分.管理 积分.查看
     */
    public function actionIndex() {}

    /**
     * 获取积分列表
     * @permission 积分.管理 积分.查看
     */
    public function actionList()
    {
        $where = [];
        $name = $this->post_data['name'] ?? '';
        if ($name) {
            $user_id_in = db_get("user", "id", ['phone[~]' => $name, 'LIMIT' => 500, 'ORDER' => ['id' => 'DESC']]);
            $where['user_id'] = $user_id_in ?: [-1];
        }
        $where['ORDER'] = ['id' => 'DESC'];
        $list = $this->model->point->pager($where);

        json($list);
    }

    /**
     * 给用户主动发放积分
     * @permission 积分.管理
     */
    public function actionAdd()
    {
        $phone = $this->post_data['phone'];
        $point = $this->post_data['point'];
        $title = $this->post_data['title'];
        if ($point <= 0) {
            json_error(['msg' => lang('积分不能小于等于0')]);
        }
        $user_id = db_get_one("user", "id", ['phone' => $phone]);
        if (!$user_id) {
            json_error(['msg' => lang('用户不存在')]);
        }
        db_action(function () use ($user_id, $point, $title) {
            add_point($user_id, $point, $type = 'gift', $title, $desc = '');
        });
        json_success(['msg' => lang('发放成功')]);
    }
    /**
     *  获取积分历史列表
     *  @permission 积分.管理 积分.查看
     */
    public function actionHis()
    {
        $user_id = (int)$_GET['user_id'];
        $this->view_data['user_id'] = $user_id;
        $user = get_user($user_id);
        $name = $user['phone'];
        $this->view_data['name'] = $name;
    }

    /**
     *  获取积分历史列表
     *  @permission 积分.管理 积分.查看
     */
    public function actionViewHis()
    {
        $where = [];
        $user_id = (int)$_GET['user_id'];
        $where['ORDER'] = ['id' => 'DESC'];
        $where['user_id'] = $user_id;
        $list = $this->model->point_his->pager($where);
        json($list);
    }
}
